home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Problem with stringcopy
- Date: Tue, 09 Jan 96 13:57:59 GMT
- Organization: none
- Message-ID: <821195879snz@genesis.demon.co.uk>
- References: <4clguu$9fs@eagle.novo.dk> <820933963snz@genesis.demon.co.uk> <4cq9dr$if9@ns.RezoNet.NET> <4cqppv$1quo@news.gate.net>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <4cqppv$1quo@news.gate.net> bhutto@gate.net "William Hutto" writes:
-
- >In article <4cq9dr$if9@ns.RezoNet.NET>,
- > ray@ultimate-tech.com (Ray Dunn) wrote:
- >>In referenced article, Lawrence Kirby says...
- >>>Morten Brun writes:
- >>>
- >>>>How do i do a partial stringcopy i.e. copy from a specific position
- >>>>in a string and a certain numbers of bytes. I am looking for a
- >>>>function like target = Stringcopy(source, startpos, length)
- >>>
- >>>target[0] = '\0';
- >>>strncat(target, source+startpos, length);
- >>
- >>....but use strncpy if you are overwriting some existing characters in
- >>target and don't want the target string to terminate after the copied
- >>characters.
-
- memcpy is more commonly used in situations like this (when you are dealing
- with possibly non null-terminated sequences of characters you usually
- have the length available separately).
-
- >Considering strncpy()'s shortcomings, I amend my code:
- >
- >char destination[ > max_length];
- >
- > strncpy(destination,&source[startpos],max_length);
- > destination[max_length]='\0';
-
- But once you've got to that you're probably better off with the strncat
- version unless you explicitly want the destination filled with trailing
- null characters all the way up to destination+max_length.
-
- strncpy works well when used for its intended purpose (writing to a
- fixed width array where 'strings' shorter than the array size are padded
- to the full length with null characters). Once such a 'semi-string' is
- created it is a fixed width datastructure and is naturally copied around
- with memcpy, compared with memcmp etc. C also directly supports outputting
- such datastructures with printf("%.*s", width, semistring);
-
- strncpy is rarely useful for anything else.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-